<template>
  <u-upload v-if="slotFlag" :accept="accept" :fileList="fileList" @afterRead="afterRead" @delete="deletePic" multiple
            :maxCount="props.limit" :width="props.width" :height="props.height" :upload-text="_uploadText"
            :disabled="disabled">
    <slot></slot>
  </u-upload>
  <u-upload v-else :accept="accept" :fileList="fileList" @afterRead="afterRead" @delete="deletePic" multiple
            :maxCount="props.limit" :width="props.width" :height="props.height" :upload-text="_uploadText"
            :disabled="disabled">
  </u-upload>
</template>

<script setup>

import * as dialog from '@/qly/dialog'

const props = defineProps({
  modelValue: {
    type: Array,
    default: null,
  },
  accept: {
    type: String,
    default: 'image'
  },
  limit: {
    type: Number,
    default: 9
  },
  width: {
    type: String,
    default: '192rpx'
  },
  height: {
    type: String,
    default: '192rpx'
  },
  uploadText: {
    type: String,
    default: null
  },
  disabled: {
    type: Boolean,
    default: false
  },
  slotFlag: {
    type: Boolean,
    default: false
  }
})

const emits = defineEmits(['update:modelValue'])
const value = computed({
  get() {
    console.log('props.modelValue',props.modelValue)
    return props.modelValue
  },
  set(val) {
    emits('update:modelValue', val)
  }
})

const _uploadText = computed(() => {
  if (props.uploadText) {
    return props.uploadText
  } else if (props.accept === 'image') {
    return '上传图片'
  } else if (props.accept === 'video') {
    return '上传视频'
  } else {
    return '上传文件'
  }
})

const fileList = computed(() => {
  const _value = value.value ?? []
  return _value.map(item => {
    if (item.data) {
      return item.data
    } else {
      return {
        url: item.url,
      }
    }

  })
})

// 删除图片
const deletePic = (event) => {
  value.value.splice(event.index, 1);
};

// 新增图片
const afterRead = async (event) => {
  console.log('event',event)
  // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
  let lists = [].concat(event.file);

  if (value.value == null) {
    value.value = []
    await nextTick()
  }
  console.log('value',value.value)

  let fileListLen = value.value.length;
  lists.map((item) => {
    value.value.push({
      data: {
        ...item,
        status: 'uploading',
        message: '上传中'
      }
    });
  });
  for (let i = 0; i < lists.length; i++) {
    console.log('lists[i]',lists[i])
    await uploadImage(lists[i].file.path).then(result => {
      let item = value.value[fileListLen];
      value.value.splice(fileListLen, 1, {
        url:result,
        data: {
          ...item.data,
          status: 'success',
          message: '',
        },
      });
      fileListLen++;
    }).catch(() => {
      value.value.splice(fileListLen, 1);
    })
  }
};

const uploadImage=async (filePath)=>{
  console.log('filePath',filePath)
  return new Promise((resolve,reject)=>{
    uni.uploadFile({
      url: 'https://tongwang.cc/api/Upload/Uploads',
      filePath,
      name: 'file',
      header:{
      },
      formData: {
        token:qly.storage.storageRef('token').value,
        uid:qly.storage.storageRef('uid').value
      },
      success: async (res) => {

        const result=JSON.parse(res.data)
        console.log('图片',result)

        const fullurl=JSON.parse(res.data).data.urlImg
        console.log('fullurl',fullurl)
        resolve(fullurl)
      },
      fail: async (err) => {
        console.log('err',err)
        await dialog.toast({
          title: '上传失败'
        })
        reject('上传失败')
      }
    })
  })


}
</script>

<style scoped>

</style>
